from django.shortcuts import render, redirect
from django.http import HttpResponse
from ..models import Department, UserInfo, PrettyNum
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
from openpyxl import load_workbook

def depart_list(request):
    """部门列表"""
    # 去数据库获取所有部门列表
    data_list = Department.objects.all()
    page_object = Pagination(request, data_list)
    page_string = page_object.html()
    return render(request, 'depart_list.html', {'data_list': data_list, "page_string": page_string})

def depart_add(request):
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    title = request.POST.get('title')
    Department.objects.create(title=title)
    return redirect('/depart/list/')

def depart_delete(request):
    nid = request.GET.get("nid")
    Department.objects.filter(id=nid).delete()
    return redirect('/depart/list/')

def depart_edit(request, nid):
    """修改部门"""
    if request.method == 'GET':
        # 根据nid，获取数据querySet<[obj, obj]>
        row_obj = Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {"row_obj": row_obj})
    title = request.POST.get("title")
    Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')

@csrf_exempt
def depart_multi(request):
    file_object = request.FILES.get('exc')
    wb = load_workbook(file_object)
    sheet = wb.worksheets[0]
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        exists = Department.objects.filter(title=text).exists()
        if exists: continue
        Department.objects.create(title=text)
    return redirect('/depart/list/')